<?php

namespace app\company\controller;

use app\common\controller\CompanyController;
use app\common\enum\order\PayType;
use app\common\enum\order\ReceiveType;
use app\common\model\DeliveryLog;
use app\common\model\Driver;
use app\common\model\Dealer;
use app\common\model\AccountRecord;
use app\common\service\annotation\ControllerAnnotation;
use think\App;
use think\response\Json;

/**
 * @ControllerAnnotation(title="对账")
 */
class Account extends CompanyController
{
    private array $where;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new AccountRecord();
        $this->where = ['AccountRecord.company_id' => $this->companyId];
    }

    /**
     * 司机对账记录
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function driverList(): Json
    {
        // 别删，说不定得改回去
//        $list = $this->model->with([
//            'driver' => function ($query) {
//                $query->field('id, name');
//            },
//            'detail' => function ($query) {
//                $query->with([
//                    'store' => function ($query) {
//                        $query->field('id, name');
//                    }
//                ])->where('pay_type', 'in', [PayType::CASH, PayType::BANK]);
//            },
//        ])->where('payee_type', AccountRecord::DRIVER)
//            ->where($this->where)
//            ->hasWhere('driver', function ($vo) use ($where) {
//                if (!empty($where)) $vo->where('name', 'like', $where[0][2]);
//            })
//            ->paginate($limit);

        [$limit, $wheres] = $this->buildSearchParams();
        $driver_where = [];
        foreach ($wheres as $k => $where) {
            if ($where[0] == 'name') {
                $driver_where[] = ['name', 'like', $where[2]];
                unset($wheres[$k]);
            }
        }
        $deliveryLogModel = new DeliveryLog();
        $list = (new Driver())->field('id,name')->where('company_id', $this->companyId)->where($driver_where)->paginate($limit)->each(function ($item) use($wheres,$deliveryLogModel) {
//            $sql = $deliveryLogModel->where('driver_id',$item->id)->where($where);
            // 订单ID集合（方便后期获取查询用）
            $item->order_ids = implode(',',$deliveryLogModel->where('driver_id',$item->id)->where($wheres)->column('company_order_id'));
            // 配送订单金额
            $item->order_money = $deliveryLogModel->where('driver_id',$item->id)->where($wheres)->sum('order_amount');
            // 配送现结金额
            $item->now_money = $deliveryLogModel->where('driver_id',$item->id)->where($wheres)->where('receive_type',ReceiveType::NOW)->sum('money');
            $item->now_ids = implode(',',$deliveryLogModel->where('driver_id',$item->id)->where($wheres)->where('receive_type',ReceiveType::NOW)->column('company_order_id'));
            // 配送挂账金额
            $item->gz_money = $deliveryLogModel->where('driver_id',$item->id)->where($wheres)->where('pay_type',PayType::GZ)->sum('delivery_amount');
            $item->gz_ids = implode(',',$deliveryLogModel->where('driver_id',$item->id)->where($wheres)->where('pay_type',PayType::GZ)->column('company_order_id'));
            // 配送账期金额
            $item->zq_money = $deliveryLogModel->where('driver_id',$item->id)->where($wheres)->where('receive_type',ReceiveType::ZQ)->sum('delivery_amount');
            $item->zq_ids = implode(',',$deliveryLogModel->where('driver_id',$item->id)->where($wheres)->where('receive_type',ReceiveType::ZQ)->column('company_order_id'));
            // 配送预付款金额
            $item->yc_money = $deliveryLogModel->where('driver_id',$item->id)->where($wheres)->where('receive_type',ReceiveType::YC)->sum('delivery_amount');
            $item->yc_ids = implode(',',$deliveryLogModel->where('driver_id',$item->id)->where($wheres)->where('receive_type',ReceiveType::YC)->column('company_order_id'));
            // 配送现金收款
            $item->cash_money = $deliveryLogModel->where('driver_id',$item->id)->where($wheres)->where('pay_type',PayType::CASH)->sum('money');
            $item->cash_ids = implode(',',$deliveryLogModel->where('driver_id',$item->id)->where($wheres)->where('pay_type',PayType::CASH)->column('company_order_id'));
            // 配送对公收款
            $item->bank_money = $deliveryLogModel->where('driver_id',$item->id)->where($wheres)->where('pay_type',PayType::BANK)->sum('money');
            $item->bank_ids = implode(',',$deliveryLogModel->where('driver_id',$item->id)->where($wheres)->where('pay_type',PayType::BANK)->column('company_order_id'));
            // 退货订单金额
            $item->th_money = 0;
            $item->th_ids = implode(',',[]);
        });
        return $this->success($list);
    }

    /**
     * 业务员对账记录
     * @return Json
     * @throws \think\db\exception\DbException
     */
    public function salesmanList(): Json
    {
        [$limit, $where] = $this->buildSearchParams();
        $list = $this->model->with([
            'salesman' => function ($query) {
                $query->field('id, rename');
            },
            'detail' => function ($query) {
                $query->with([
                    'store' => function ($query) {
                        $query->field('id, name');
                    }
                ])->where('pay_type', 'in', [PayType::CASH, PayType::BANK]);
            },
            'refund' => function ($query) {
                $query->with([
                    'store' => function ($query) {
                        $query->field('id, name');
                    }
                ])->where('status', 1);
            },
        ])->where('payee_type', AccountRecord::SALESMAN)
            ->where($this->where)
            ->hasWhere('salesman', function ($vo) use ($where) {
                if (!empty($where)) $vo->where('rename', 'like', $where[0][2]);
            })
            ->paginate($limit);
        return $this->success($list);
    }

    public function dealerList(): Json
    {
        [$limit, $wheres] = $this->buildSearchParams();
        // 别删，说不定得改回去
//        $list = $this->model->with([
//            'dealer' => function ($query) {
//                $query->field('id, name,tc_rate,tp_rate,tx_rate');
//            },
//            'fz',
//        ])->where('payee_type', AccountRecord::DEALER)
//            ->where($this->where)
//            ->hasWhere('dealer', function ($vo) use ($where) {
//                if (!empty($where)) $vo->where('name', 'like', $where[0][2]);
//            })
//            ->paginate($limit);
//
//        foreach ($list as $k => &$v) {
//            $fz_money = 0;
//            foreach ($v->fz as $k2 => &$v2) {
//
//                $v2->tc_rate_money = isset($v2->tc_rate) ? bcdiv(bcmul($v2->out_money , $v2->tc_rate) ,100,2) : 0;
//                $v2->tp_rate_money = isset($v2->tp_rate) ? bcdiv(bcmul($v2->out_money , $v2->tp_rate) ,100,2) : 0;
//                $v2->tx_rate_money = isset($v2->tx_rate) ? bcdiv(bcmul($v2->out_money , $v2->tx_rate) ,100,2) : 0;
//                $v2->money = bcadd(bcadd($v2->tc_rate_money , $v2->tp_rate_money) ,$v2->tx_rate_money,2);
//                $fz_money += $v2->money;
//            }
//
//            //待分账金额
//            $v->fz_money = sprintf('%.2f',$fz_money) ;
//
//        }
        $dealer_where = [];
        foreach ($wheres as $k => $where) {
            if ($where[0] == 'name') {
                $dealer_where[] = ['name', 'like', $where[2]];
                unset($wheres[$k]);
            }
        }
        $deliveryLogModel = new DeliveryLog();
        $list = (new Dealer())->field('id,name')->where('company_id', $this->companyId)->where($dealer_where)->paginate($limit)->each(function ($item) use($wheres,$deliveryLogModel) {
//            $sql = $deliveryLogModel->where('driver_id',$item->id)->where($where);
            // 订单ID集合（方便后期获取查询用）
            $item->order_ids = implode(',',$deliveryLogModel->where('dealer_id',$item->id)->where($wheres)->column('company_order_id'));
            // 配送订单金额
            $item->order_money = $deliveryLogModel->where('dealer_id',$item->id)->where($wheres)->sum('order_amount');
            // 配送现结金额
            $item->now_money = $deliveryLogModel->where('dealer_id',$item->id)->where($wheres)->where('receive_type',ReceiveType::NOW)->sum('money');
            $item->now_ids = implode(',',$deliveryLogModel->where('dealer_id',$item->id)->where($wheres)->where('receive_type',ReceiveType::NOW)->column('company_order_id'));
            // 配送挂账金额
            $item->gz_money = $deliveryLogModel->where('dealer_id',$item->id)->where($wheres)->where('pay_type',PayType::GZ)->sum('delivery_amount');
            $item->gz_ids = implode(',',$deliveryLogModel->where('dealer_id',$item->id)->where($wheres)->where('pay_type',PayType::GZ)->column('company_order_id'));
            // 配送账期金额
            $item->zq_money = $deliveryLogModel->where('dealer_id',$item->id)->where($wheres)->where('receive_type',ReceiveType::ZQ)->sum('delivery_amount');
            $item->zq_ids = implode(',',$deliveryLogModel->where('dealer_id',$item->id)->where($wheres)->where('receive_type',ReceiveType::ZQ)->column('company_order_id'));
            // 配送预付款金额
            $item->yc_money = $deliveryLogModel->where('dealer_id',$item->id)->where($wheres)->where('receive_type',ReceiveType::YC)->sum('delivery_amount');
            $item->yc_ids = implode(',',$deliveryLogModel->where('dealer_id',$item->id)->where($wheres)->where('receive_type',ReceiveType::YC)->column('company_order_id'));
            // 退货订单金额
            $item->th_money = 0;
            $item->th_ids = implode(',',[]);
        });
        return $this->success($list);
    }
}